package com.yunhuakeji.wddx.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class FenLeiTools
{
	private List<Map<String, String>> list;
	@SuppressWarnings("unused")
	private List<Map<String, String>> temp_list = new ArrayList<>();
	private String name, childName;
	private String[] needName, titleName;

	public static void main(String[] args)
	{
		new DataBaseThreadTools();
		System.out.println(new FenLeiTools(new DBHelper3().select("select m.result_id,j.result_describe,j.result_character,m.trade_id,m.trade_name,n.profession_id,n.profession_name,n.post_id,n.post_name from XTGL_EVALUATING_LIBRARY m,XTGL_PROFESSION_LIBRARY n,XTGL_EVALUATING_DESCRIBE j where m.result_id='ISTJ' and m.profession_id=n.profession_id and m.result_id=j.result_id order by m.trade_id,n.profession_id,n.post_id"), "trade_id", "job", new String[]
		{
			"trade_name"
		}, new String[]
		{
			"profession_name"
		}).doFenLei().toString());
	}

	public FenLeiTools(List<Map<String, String>> list, String name, String childName, String[] titleName, String... needName)
	{
		this.titleName = titleName;
		this.list = list;
		this.name = name;
		this.needName = needName;
		this.childName = childName;
	}

	public JSONArray doFenLei()
	{
		Object temp = "";
		JSONArray jsa = new JSONArray();
		for (int i = 0, length = list.size(); i < length; i++)
		{
			if (!list.get(i).get(name).equals(temp))
			{
				temp = list.get(i).get(name);
				jsa.add(new JSONObject());
				jsa.getJSONObject(jsa.size() - 1).accumulateAll(addTitleMap(list.get(i)));
			}
			jsa.getJSONObject(jsa.size() - 1).element(childName, new JSONArray());
			jsa.getJSONObject(jsa.size() - 1).getJSONArray(childName).add(addTempMap(list.get(i)));
			
		}
		return jsa;
	}

	private Map<String, Object> addTitleMap(Map<String, String> itemMap)
	{
		Map<String, Object> map = new HashMap<>();
		for (int i = 0; i < titleName.length; i++)
		{
			map.put(titleName[i], itemMap.get(titleName[i]));
		}
		return map;
	}

	private Map<String, Object> addTempMap(Map<String, String> itemMap)
	{
		Map<String, Object> map = new HashMap<>();
		for (int i = 0; i < needName.length; i++)
		{
			map.put(needName[i], itemMap.get(needName[i]));
		}
		return map;
	}

}